#include "peonyrabbitvcsmenuplugin.h"
#include "statuschecker.h"
#include "rabbitvcsmenuhelper.h"

#include <QAction>
#include <QDBusConnection>
#include <QDBusInterface>
#include <QProcess>

#include <QUrl>
#include <QHash>

#include <QTranslator>
#include <QLocale>
#include <QApplication>

#include <QUrl>

#include <QDebug>

#define TRANSLATION_PATH "/usr/share/peony-extensions/rabbitvcs"

PeonyRabbitVCSMenuPlugin::PeonyRabbitVCSMenuPlugin(QObject *parent)
    : QObject(parent)
{
    auto translator = new QTranslator(this);
    bool loaded = translator->load(TRANSLATION_PATH + QString("/peony-rabbitvcs-menu_%1").arg(QLocale::system().name()));
    QApplication::installTranslator(translator);

    QDBusInterface iface(SERVICE, OBJECT_PATH, INTERFACE);
    if (!iface.isValid()) {
        QProcess p;
        p.setProgram("/usr/bin/python3");
        p.setArguments(QStringList()<<"/usr/lib/python3/dist-packages/rabbitvcs/services/checkerservice.py");
        p.startDetached();
        p.waitForFinished();
    }
}

QList<QAction *> PeonyRabbitVCSMenuPlugin::menuActions(Peony::MenuPluginInterface::Types types, const QString &uri, const QStringList &selectionUris)
{
    QList<QAction *> l;
    if (types == SideBar)
        return l;

    if (!uri.startsWith("file:///")) {
        return l;
    }

    QStringList paths;
    if (selectionUris.isEmpty()) {
        QUrl url = uri;
        paths.append(url.path());
    } else {
        for (QString selection : selectionUris) {
            QUrl url = selection;
            paths.append(url.path());
        }
    }

    auto conditions = StatusChecker::getInstance()->generateMenuConditions(paths);
    l<<RabbitVCSMenuHelper::getActionsFromConditions(paths, conditions);

    if (!qgetenv("RABBITVCS_PEONY_DEBUG").isEmpty()) {
        auto action = new QAction("test vcs checkstatus");
        connect(action, &QAction::triggered, this, [=]{
            QHash<QString, QString> hash;
            for (auto path : paths) {
                auto value = StatusChecker::getInstance()->checkStatus(path, true, true, true);
                hash.insert(path, value);
            }
            qDebug()<<hash;
        });
        l<<action;

        action = new QAction("test vcs generate menu conditions");
        connect(action, &QAction::triggered, this, [=]{
            auto value = StatusChecker::getInstance()->generateMenuConditions(paths);
            qDebug()<<paths<<value;
        });
        l<<action;
    }

    return l;
}
